<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use think\Db;
use app\admin\model\Admin;

class ApiindexController extends CommonController
{
    /*====自动定位Start=====*/
    /**
     * location 自动定位返回id
     * $location  地区名称
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return 返回数组
     */
    public function location(){
        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            $returnData['status'] = 301;
//            $returnData['msg'] = "Token失效！请重新登录！";
//            return json_encode($returnData);
//        }
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('ew_area')
                ->where('district',$sheng)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('ew_area')
                ->where('district',$shi)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('ew_area')
                ->where('district',$qu)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json_encode(['status'=>200,'msg'=>$res]);
    }

    /**
     * 获取所有
     * @return string
     */
    public function getCitys(){
//        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            $returnData['status'] = 301;
//            $returnData['msg'] = "Token失效！请重新登录！";
//            return json_encode($returnData);
//        }
        header("Content-type:text/html;charset=utf-8");
        $res = Db::table('ew_area')
            ->where('level',2)
            ->field('district_id id,district city')
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }

    /*====自动定位End=====*/
    /**
     * 轮播图
     * @return string
     */
    public function getLunbo()
    {
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $ls = Db::table('ew_lunbo')
            ->where('lb_status',1)
            ->field('lb_id,lb_name,lb_image,lb_status,lb_time')
            ->order('lb_time DESC')
            ->limit('0,5')
            ->select();
        return json_encode(['status'=>200,'msg'=>$ls]);
    }
    /**
     * 轮播图详情
     * @return string
     */
    public function getLunboInfo()
    {
        extract(input());
        $ls = Db::table('ew_lunbo')
            ->where('lb_id',$lb_id)
            ->find();
        return json_encode(['status'=>200,'msg'=>$ls]);
    }


    /**
     * 首页三类的列表数据获取：含搜索：search 、含某个用户的职位列表：uid
     * type,page,
     * zhouqi,
     * order(默认是时间倒叙：1)
     * 1时间倒叙，2正序，3距离近到远，4远到近，5薪资高到低，6低到高
     * @return string
     */
    public function indexData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //====实时更新记录最后一次的登陆时间======
        if($user_id > 0){
            Db::table('ew_u_user')->where('user_id',$user_id)->update(['user_last_login_date'=>date('Y-m-d')]);
        }
        //=====end====
        if($type != 1 && $type != 2 && $type != 3){
            return json_encode(['status'=>0,'msg'=>'未知请求']);
        }
        //==============排序====================
        if(!isset($order) || $order<1 || $order>6){
            return json_encode(['status'=>0,'msg'=>'未知的排序请求']);
        }
        $where = array();
        $where['order'] = $order;
        if(isset($lat) && isset($lon) && $lat && $lon){
            $where['lat'] = $lat;
            $where['lon'] = $lon;
        }else{
            $where['lat'] = 0.1;
            $where['lon'] = 0.1;
        }
        //=================end===================
        $where['job_type'] = $type;
        $where['job_status'] = 1;
        if(isset($shi) && $shi != ''){$where['job_shi'] = $shi;}
        if(isset($zhouqi) && $zhouqi != ''){$where['job_com_find_zhouqi'] = $zhouqi;}
        if(isset($search)){$where['job_name'] = $search;}//仅此行附带搜索
        //=====招聘列表=====================
        if(isset($uid)){
            $where['job_user_id'] = $uid;
            if(isset($shi) && $shi != ''){unset($where['job_shi']);}
        }
        //=====end=====
        $data = $this->getJobData($type,$where,$page);
        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * 首页三类的单条信息数据详情
     * job_id,type
     * @return string
     */
    public function indexDataInfo(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if($user_id !=0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == false){
                $returnData['status'] = 301;
                $returnData['msg'] = "Token失效！请重新登录！";
                return json_encode($returnData);
            }
        }
        $field = 'job_id,user_id,job_user_id,job_type,job_phone,job_sheng,job_shi,job_qu,job_name,job_status,job_address,job_content,u.district sheng,ua.district shi,uaa.district qu,job_money_min,job_money_max,job_createtime';
        $field .= ',job_year,job_weixin,job_qq,job_school,job_age_min,job_age_max,job_sex,user_username,user_image';
        $field .= ',job_peple,job_com_find_zhouqi,job_zhouqi_year';
        $field .= ',job_beautiful,job_zhouqi_order,job_zhi,job_whatfor,job_url';
        if($type == 1){
            $field .= ',user_one_star';
            $field .= ',user_one_num';
        }elseif($type == 2){
            $field .= ',user_company,user_company_logo,job_com_name,job_com_jianjie,job_com_address,user_two_star';
            $field .= ',user_two_num,job_com_qu,job_com_sheng,job_com_shi';
        }elseif($type == 3){
            $field .= ',user_thr_star';
            $field .= ',user_thr_num';
        }else{
            return json_encode(['status'=>0,'msg'=>'未知请求']);
        }
        $data = Db::table('ew_job')->alias('j')
            ->join('ew_u_user uu','j.job_user_id=uu.user_id','LEFT')
            ->join('ew_area u','j.job_sheng=u.district_id','LEFT')
            ->join('ew_area ua','j.job_shi=ua.district_id','LEFT')
            ->join('ew_area uaa','j.job_qu=uaa.district_id','LEFT')
            ->where('job_id',$job_id)->field($field)
            ->find();
        if($type == 2){//如果是公司的话有公司地址
            $data['com_sheng'] = Db::table('ew_area')->where('district_id',$data['job_com_sheng'])->find()['district'];
            $data['com_shi'] = Db::table('ew_area')->where('district_id',$data['job_com_shi'])->find()['district'];
            $data['com_qu'] = Db::table('ew_area')->where('district_id',$data['job_com_qu'])->find()['district'];
        }
        $like = 1;
        $res = Db::table('ew_attention_job')
            ->where('attention_user_id',$user_id)
            ->where('attention_job_id',$job_id)
            ->find();
        if($res){$like = 2;}
        //=======是不是我的好友======
//        $whofri = $this->getFriendStatus($data['job_user_id'],$user_id);
        if($data['job_beautiful']){
            $data['job_beautiful'] = trim($data['job_beautiful'],',');
            $data['job_beautiful'] = explode(',',$data['job_beautiful']);
        }else{
            $data['job_beautiful'] = array();
        }
        //========end=====
        return json_encode(['status'=>200,'msg'=>$data,'like'=>$like]);
    }
    /**
     * 收藏或者取消收藏职位
     * job_id
     * @return string
     */
    public function attentionJob(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }

        $res = Db::table('ew_attention_job')
            ->where('attention_user_id',$user_id)
            ->where('attention_job_id',$job_id)
            ->find();
        if($res){
            $res2 = Db::table('ew_attention_job')
                ->where('attention_user_id',$user_id)
                ->where('attention_job_id',$job_id)
                ->delete();
        }else{
            $res2 = Db::table('ew_attention_job')
                ->insert(['attention_user_id'=>$user_id,'attention_job_id'=>$job_id]);
        }
        if($res2){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }

    /**
     * 职位评论的阶梯式展示
     * uid（如果:这个是这个职位的发布人的id），type，page
     * @return string
     */
    public function jobComment(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if($user_id !=0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == false){
                $returnData['status'] = 301;
                $returnData['msg'] = "Token失效！请重新登录！";
                return json_encode($returnData);
            }
        }
        //详情页有两条
        $pageNum = 10;
        if(isset($length) && $length){
            $pageNum = $length;
        }
        $coms = Db::table('ew_comment')->alias('c')
            ->join('ew_u_user u','c.comment_reply_user_id=u.user_id','LEFT')
            ->where('comment_user_id',$uid)
            ->where('comment_type',$type)
            ->field('user_id,user_image,user_username,comment_id,comment_content,comment_score,comment_time')
            ->order('comment_time DESC')
            ->limit(($page-1)*10,$pageNum)
            ->select();
        $num = count($coms);
//        二层评论
        if($coms){
            foreach ($coms as $k=>$v){
                $comtts = Db::table('ew_comment_tt')->alias('ct')
                    ->join('ew_u_user u','ct.comtt_one_user_id=u.user_id','LEFT')
                    ->join('ew_u_user u2','ct.comtt_reply_user_id=u2.user_id','LEFT')
                    ->field('u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name,comtt_content,comtt_time')
                    ->where('comtt_comment_id',$v['comment_id'])
                    ->limit(0,5)
                    ->select();
                $coms[$k]['under'] = $comtts;
            }
        }
        return json_encode(['status'=>200,'msg'=>$coms,'num'=>$num]);

    }
    /**
     * 职位评论的第二层回复：第二页开始
     *  （第一层的id），page
     * @return string
     */
    public function jobCommentTwo(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
//        二层评论
        $comtts = Db::table('ew_comment_tt')->alias('ct')
            ->join('ew_u_user u','ct.comtt_one_user_id=u.user_id','LEFT')
            ->join('ew_u_user u2','ct.comtt_reply_user_id=u2.user_id','LEFT')
            ->field('u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name,comtt_content,comtt_time')
            ->where('comtt_comment_id',$comment_id)
            ->limit(($page-1)*5,5)
            ->select();
        return json_encode(['status'=>200,'msg'=>$comtts]);
    }
    /**
     * 直接评论职位的
     * uid,content,score,type
     * @return string
     */
    public function insertCommentUp(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($type != 1 && $type != 2 && $type != 3){
            return json_encode(['status'=>0,'msg'=>'未知请求']);
        }
        // 启动事务
        Db::startTrans();
        try{
        $data = array();
        $data['comment_user_id'] = $uid;
        $data['comment_content'] = $content;
        $data['comment_reply_user_id'] = $user_id;
        $data['comment_score'] = $score;
        $data['comment_type'] = $type;
        $data['comment_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_comment')->insert($data);
        //========================
        $coms = Db::table('ew_comment')
            ->where('comment_user_id',$uid)
            ->where('comment_type',$type)
            ->field('sum(comment_score) star,count(*) many')
            ->find();
        $many = $coms['many'];
        $star = sprintf("%.1f", ($coms['star']+5)/($many+1));
        $update = array();
        if($type == 1){
            $update['user_one_star'] = $star;
            $update['user_one_num'] = $many;
        }
        if($type == 2){
            $update['user_two_star'] = $star;
            $update['user_two_num'] = $many;
        }
        if($type == 3){
            $update['user_thr_star'] = $star;
            $update['user_thr_num'] = $many;
        }
        Db::table('ew_u_user')->where('user_id',$uid)->update($update);

        /*-----------------加入消息表------------------*/
        $notice = array();
        $notice['n_who'] = $uid;//给谁留言
        $notice['n_user_id'] = $uid;//给谁留言
        $notice['n_reply_user_id'] = $user_id;//谁留言
            $time = date('Y-m-d H:i:s');
        $notice['n_title'] = "在{$time}的时候给您评论了，评论内容：{$content}";
        $notice['n_time'] = $time;
        $notice['n_where'] = 2;
        $notice['n_type'] = $type;
        Db::table('ew_notice')->insert($notice);
        /*----------------------end------------------*/

        //========================
            // 提交事务
            Db::commit();
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("$uid","{$name}给您评论了",array('aa'=>'bb'),1);
            /*-----------end------------*/
            return json_encode(['status'=>200,'msg'=>'成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }

    /**
     * 直接回复——one
     * comment_id，content
     * @return string
     */
    public function insertCommentOne(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['comtt_comment_id'] = $comment_id;
        $data['comtt_content'] = $content;
        $data['comtt_one_user_id'] = $user_id;
        $data['comtt_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_comment_tt')->insert($data);
        if($res){
            /*-----------------加入消息表------------------*/
            $notice = array();
            $notice['n_where'] = 2;
                $need = Db::table('ew_comment')->where('comment_id',$comment_id)->field('comment_reply_user_id,comment_type,comment_user_id')->find();
                $time = date('Y-m-d H:i:s');
            $notice['n_time'] = $time;
            $notice['n_who'] = $need['comment_user_id'];
            $notice['n_user_id'] = $need['comment_reply_user_id'];//给谁留言
            $notice['n_reply_user_id'] = $user_id;//谁留言
            $notice['n_title'] = "在{$time}的时候给您回复了，回复内容：{$content}";
            $notice['n_type'] = $need['comment_type'];
            Db::table('ew_notice')->insert($notice);
            /*----------------------end------------------*/
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("{$need['comment_reply_user_id']}","{$name}回复了您的评论",array('aa'=>'bb'),1);
            /*-----------end------------*/

            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作成功']);
        }
    }
    /**
     * 直接回复的回复——two
     * comment_id，content，uid2
     * @return string
     */
    public function insertCommentTwo(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['comtt_comment_id'] = $comment_id;
        $data['comtt_content'] = $content;
        $data['comtt_one_user_id'] = $uid2;
        $data['comtt_reply_user_id'] = $user_id;
        $data['comtt_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_comment_tt')->insert($data);
        if($res){

            /*-----------------加入消息表------------------*/
            $notice = array();
            $notice['n_where'] = 2;
                $need = Db::table('ew_comment')->where('comment_id',$comment_id)->field('comment_reply_user_id,comment_type,comment_user_id')->find();
                $time = date('Y-m-d H:i:s');
            $notice['n_time'] = $time;
            $notice['n_who'] = $need['comment_user_id'];
            $notice['n_user_id'] = $uid2;//给谁留言
            $notice['n_reply_user_id'] = $user_id;//谁留言
            $notice['n_title'] = "在{$time}的时候给您回复了，回复内容：{$content}";
            $notice['n_type'] = $need['comment_type'];
            Db::table('ew_notice')->insert($notice);
            /*----------------------end------------------*/
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("$uid2","{$name}回复了您",array('aa'=>'bb'),1);
            /*-----------end------------*/

            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作成功']);
        }
    }

    /**
     * 获取所有和我有关的消息
     * comment_id，content，uid2
     * @return string
     */
    public function getNotice(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $time = Db::table('ew_u_user')->where('user_id', $user_id)->value('user_time');
        if($type == 1) {
            $mynids = Db::table('ew_see_notice')->where('userid', $user_id)->value('nids');
            if ($mynids) {
                $data = Db::table('ew_notice')->alias('n')
                    ->join('ew_u_user u', 'n.n_reply_user_id=u.user_id', 'LEFT')
                    ->where('n_id', 'not in', "{$mynids}")
                    ->where('n_where', 'in', '1,2,3,5')
                    ->where('n_time', '>=', $time)
                    ->where(function ($query) use ($user_id) {
                        $query->where('n_user_id', $user_id)->whereOr('n_where', 1);
                    })
                    ->field('n.*,user_username')
                    ->order('n_time DESC')
                    ->limit(($page - 1) * 10, 10)
                    ->select();
            } else {
                $data = Db::table('ew_notice')->alias('n')
                    ->join('ew_u_user u', 'n.n_reply_user_id=u.user_id', 'LEFT')
//                    ->where('n_user_id', $user_id)
                    ->where(function ($query) use ($time) {
                        $query->where('n_where', 1)->where('n_time', '>=', $time);
                    })
                    ->whereOr(function ($query) use ($user_id,$time) {
                        $query->where('n_user_id', $user_id)->where('n_where', 'in', '2,3,5')->where('n_time', '>=', $time);
                    })
                    ->field('n.*,user_username')
                    ->order('n_time DESC')
                    ->limit(($page - 1) * 10, 10)
                    ->select();
            }
        }else{
            $data = Db::table('ew_notice')->alias('n')
                ->join('ew_u_user u', 'n.n_reply_user_id=u.user_id', 'LEFT')
                ->where('n_user_id', $user_id)
                ->where('n_where', 4)
                ->field('n.*,user_username')
                ->order('n_time DESC')
                ->limit(($page - 1) * 10, 10)
                ->select();
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }

    public function getNoticeInfo()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_notice')
        ->where('n_id',$n_id)
        ->find();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    public function deleteNotice()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = Db::table('ew_notice')
        ->where('n_id',$n_id)
        ->value('n_where');
        if($where != 1){
            if($where == 4){
               $v = Db::table('ew_notice')
                    ->where('n_id',$n_id)->field('n_user_id,n_reply_user_id')
                    ->find();
                $fid_2 = Db::table('ew_friend')
                    ->where('friend_user_id',$v['n_reply_user_id'])
                    ->where('friend_good_user_id',$v['n_user_id'])
                    ->where('friend_status',2)
                    ->value('friend_id');
                if($fid_2){
                    Db::table('ew_friend')
                        ->where('friend_id',$fid_2)->delete();
                }
            }
            $res = Db::table('ew_notice')
                ->where('n_id',$n_id)
                ->delete();
            if($res){
                return json_encode(['status'=>200,'msg'=>'操作成功']);
            }else{
                return json_encode(['status'=>0,'msg'=>'操作失败']);
            }
        }else{
            $nids = Db::table('ew_see_notice')->where('userid',$user_id)->value('nids');
            if($nids){
                $new = $nids . ',' . $n_id;
                Db::table('ew_see_notice')->where('userid',$user_id)->update(['nids'=>$new]);
            }else{
                Db::table('ew_see_notice')->insert(['userid'=>$user_id,'nids'=>$n_id]);
            }
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }
    }

    /**
     * 删除所有消息
     * @return string
     */
    public function deleteAllNotice()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($type == 1){//1是删除所有的信息，2是删除好友
            Db::table('ew_notice')
                ->where('n_user_id',$user_id)
                ->where('n_where','<',4)
                ->delete();
            $nids = Db::table('ew_notice')
                ->where('n_where',1)
                ->column('n_id');
            if($nids){
                $nids = implode(',',$nids);
                $have = Db::table('ew_see_notice')->where('userid',$user_id)->value('nids');
                if($have){
                    Db::table('ew_see_notice')->where('userid',$user_id)->update(['nids'=>$nids]);
                }else{
                    Db::table('ew_see_notice')->insert(['userid'=>$user_id,'nids'=>$nids]);
                }
            }
        }else{
            $uids = Db::table('ew_notice')
                ->where('n_where',4)
                ->where('n_user_id',$user_id)
                ->field('n_user_id,n_reply_user_id')
                ->select();
            if($uids){
                foreach ($uids as $v){
                    $fid_2 = Db::table('ew_friend')
                        ->where('friend_user_id',$v['n_reply_user_id'])
                        ->where('friend_good_user_id',$v['n_user_id'])
                        ->where('friend_status',2)
                        ->value('friend_id');
                    if($fid_2){
                        Db::table('ew_friend')
                            ->where('friend_id',$fid_2)->delete();
                    }
                }
                Db::table('ew_notice')
                    ->where('n_where',4)->where('n_user_id',$user_id)
                    ->delete();
            }
        }

        return json_encode(['status'=>200,'msg'=>'操作成功']);
    }

}